<template>
  <div class="home-layout">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <!-- Logo区域 -->
      <div class="sidebar-header">
        <div class="logo-container">
          <div class="logo">
            <Shield class="logo-icon" />
          </div>
          <h1 class="logo-text">防返贫系统</h1>
        </div>
      </div>

      <!-- 导航菜单 -->
      <nav class="sidebar-nav">
        <div class="nav-section">
          <h3 class="nav-section-title">主要功能</h3>
          <ul class="nav-list">
            <li class="nav-item">
              <router-link to="/dashboard" class="nav-link" active-class="nav-link-active">
                <Home class="nav-icon" />
                <span>工作台</span>
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/clues" class="nav-link" active-class="nav-link-active">
                <AlertTriangle class="nav-icon" />
                <span>线索管理</span>
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/farmers" class="nav-link" active-class="nav-link-active">
                <Users class="nav-icon" />
                <span>农户档案</span>
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/visits" class="nav-link" active-class="nav-link-active">
                <MapPin class="nav-icon" />
                <span>走访管理</span>
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/assistance" class="nav-link" active-class="nav-link-active">
                <Heart class="nav-icon" />
                <span>帮扶管理</span>
              </router-link>
            </li>
          </ul>
        </div>

        <div class="nav-section">
          <h3 class="nav-section-title">数据分析</h3>
          <ul class="nav-list">
            <li class="nav-item">
              <router-link to="/analytics" class="nav-link" active-class="nav-link-active">
                <BarChart3 class="nav-icon" />
                <span>数据统计</span>
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/reports" class="nav-link" active-class="nav-link-active">
                <FileText class="nav-icon" />
                <span>报表管理</span>
              </router-link>
            </li>
          </ul>
        </div>

        <div class="nav-section">
          <h3 class="nav-section-title">系统管理</h3>
          <ul class="nav-list">
            <li class="nav-item">
              <router-link to="/notifications" class="nav-link" active-class="nav-link-active">
                <Bell class="nav-icon" />
                <span>通知中心</span>
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/settings" class="nav-link" active-class="nav-link-active">
                <Settings class="nav-icon" />
                <span>系统设置</span>
              </router-link>
            </li>
          </ul>
        </div>
      </nav>
    </aside>

    <!-- 主体内容区域 -->
    <div class="main-container">
      <!-- 顶栏 -->
      <header class="top-header">
        <div class="header-left">
          <button class="sidebar-toggle" @click="toggleSidebar">
            <Menu class="toggle-icon" />
          </button>
          <div class="breadcrumb">
            <span class="breadcrumb-item">{{ currentPageTitle }}</span>
          </div>
        </div>

        <div class="header-right">
          <!-- 消息通知 -->
          <div
            class="header-item notification-item"
            @click="toggleNotifications"
            ref="notificationRef"
          >
            <div class="notification-icon-wrapper">
              <Bell class="header-icon" />
              <span v-if="unreadCount > 0" class="notification-badge">{{ unreadCount }}</span>
            </div>
          </div>

          <!-- 当前时间 -->
          <div class="header-item time-item">
            <Clock class="header-icon" />
            <span class="time-text">{{ formatTime(currentTime) }}</span>
          </div>

          <!-- 用户信息 -->
          <div class="header-item user-item" @click="toggleUserMenu" ref="userMenuRef">
            <div class="user-avatar">
              <img :src="user.avatar" :alt="user.name" class="avatar-img" />
            </div>
            <div class="user-info">
              <span class="user-name">{{ user.name }}</span>
              <span class="user-role">{{ user.role }}</span>
            </div>
            <ChevronDown class="dropdown-icon" />
          </div>
        </div>
      </header>

      <!-- 页面内容区域 -->
      <main class="page-content">
        <router-view />
      </main>
    </div>

    <!-- 通知弹窗 -->
    <Teleport to="body">
      <transition name="notification-fade">
        <div
          v-if="showNotificationPanel"
          class="notification-panel"
          @click.self="hideNotifications"
        >
          <div class="notification-content">
            <div class="notification-header">
              <h3>消息通知</h3>
              <button @click="hideNotifications" class="close-btn">
                <X class="close-icon" />
              </button>
            </div>
            <div class="notification-list">
              <div
                v-for="notification in notifications"
                :key="notification.id"
                class="notification-item"
                :class="{ unread: !notification.read }"
              >
                <div class="notification-content-text">
                  <h4>{{ notification.title }}</h4>
                  <p>{{ notification.content }}</p>
                  <span class="notification-time">{{ notification.time }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>
    </Teleport>

    <!-- 用户菜单弹窗 -->
    <Teleport to="body">
      <transition name="user-menu-fade">
        <div v-if="showUserMenuPanel" class="user-menu-panel" @click.self="hideUserMenu">
          <div class="user-menu-content">
            <div class="user-menu-item" @click="viewProfile">
              <User class="menu-icon" />
              <span>个人资料</span>
            </div>
            <div class="user-menu-item" @click="changePassword">
              <Lock class="menu-icon" />
              <span>修改密码</span>
            </div>
            <div class="user-menu-item logout" @click="logout">
              <LogOut class="menu-icon" />
              <span>退出登录</span>
            </div>
          </div>
        </div>
      </transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { mapActions } from 'vuex'
import { useStore } from 'vuex'
import {
  Shield,
  Home,
  AlertTriangle,
  Users,
  MapPin,
  Heart,
  BarChart3,
  FileText,
  Bell,
  Settings,
  Menu,
  Clock,
  ChevronDown,
  X,
  User,
  Lock,
  LogOut,
} from 'lucide-vue-next'

// 响应式数据
const route = useRoute()
const currentTime = ref(new Date())
const showNotificationPanel = ref(false)
const showUserMenuPanel = ref(false)
const sidebarCollapsed = ref(false)
const notificationRef = ref<HTMLElement>()
const userMenuRef = ref<HTMLElement>()
let timer: ReturnType<typeof setInterval> | null = null
const router = useRouter()
const store = useStore()

// 用户信息
const user = ref({
  name: '张三',
  role: '帮扶干部',
  avatar:
    'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=40&h=40&fit=crop&crop=face&auto=format',
})

// 通知数据
const notifications = ref([
  {
    id: '1',
    title: '新的风险线索',
    content: '李四家庭收入突然减少，需要实地核实情况',
    time: '5分钟前',
    read: false,
  },
  {
    id: '2',
    title: '帮扶计划到期提醒',
    content: '王五的帮扶计划将在3天后到期',
    time: '1小时前',
    read: false,
  },
  {
    id: '3',
    title: '系统维护通知',
    content: '系统将于今晚22:00进行维护升级',
    time: '2小时前',
    read: true,
  },
])

// 计算属性
const unreadCount = computed(() => notifications.value.filter((n) => !n.read).length)

const currentPageTitle = computed(() => {
  const titleMap: Record<string, string> = {
    '/dashboard': '工作台',
    '/clues': '线索管理',
    '/farmers': '农户档案',
    '/visits': '走访管理',
    '/assistance': '帮扶管理',
    '/analytics': '数据统计',
    '/reports': '报表管理',
    '/notifications': '通知中心',
    '/settings': '系统设置',
  }
  return titleMap[route.path] || '工作台'
})

// 方法
const formatTime = (date: Date): string => {
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

const toggleNotifications = () => {
  if (showNotificationPanel.value) {
    showNotificationPanel.value = false
  } else {
    showNotificationPanel.value = true
    showUserMenuPanel.value = false

    nextTick(() => {
      positionNotificationPanel()
    })
  }
}

const hideNotifications = () => {
  showNotificationPanel.value = false
}

const toggleUserMenu = () => {
  if (showUserMenuPanel.value) {
    showUserMenuPanel.value = false
  } else {
    showUserMenuPanel.value = true
    showNotificationPanel.value = false

    nextTick(() => {
      positionUserMenuPanel()
    })
  }
}

const hideUserMenu = () => {
  showUserMenuPanel.value = false
}

const positionNotificationPanel = () => {
  if (notificationRef.value) {
    const rect = notificationRef.value.getBoundingClientRect()
    const panel = document.querySelector('.notification-panel .notification-content') as HTMLElement
    if (panel) {
      panel.style.top = `${rect.bottom + 8}px`
      panel.style.right = `${window.innerWidth - rect.right}px`
    }
  }
}

const positionUserMenuPanel = () => {
  if (userMenuRef.value) {
    const rect = userMenuRef.value.getBoundingClientRect()
    const panel = document.querySelector('.user-menu-panel .user-menu-content') as HTMLElement
    if (panel) {
      panel.style.top = `${rect.bottom + 8}px`
      panel.style.right = `${window.innerWidth - rect.right}px`
    }
  }
}

const viewProfile = () => {
  hideUserMenu()
  console.log('查看个人资料')
}

const changePassword = () => {
  hideUserMenu()
  console.log('修改密码')
}

const logout = () => {
  hideUserMenu()

  // 清除vuex中的数据（调用store中的logout action）
  store.dispatch('logout')

  // 清除本地存储
  localStorage.clear()

  // 跳转到登录页
  router.push('/')

  console.log('退出登录')
}

// 点击外部关闭
const handleClickOutside = (event: MouseEvent) => {
  if (
    showNotificationPanel.value &&
    notificationRef.value &&
    !notificationRef.value.contains(event.target as Node)
  ) {
    const notificationPanel = document.querySelector('.notification-panel')
    if (notificationPanel && !notificationPanel.contains(event.target as Node)) {
      hideNotifications()
    }
  }

  if (
    showUserMenuPanel.value &&
    userMenuRef.value &&
    !userMenuRef.value.contains(event.target as Node)
  ) {
    const userMenuPanel = document.querySelector('.user-menu-panel')
    if (userMenuPanel && !userMenuPanel.contains(event.target as Node)) {
      hideUserMenu()
    }
  }
}

// 生命周期
onMounted(() => {
  timer = setInterval(() => {
    currentTime.value = new Date()
  }, 1000) // 每秒更新一次

  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }

  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
/* 主布局 */
.home-layout {
  display: grid;
  grid-template-columns: 280px 1fr;
  height: 100vh;
  background-color: #f8fafc;
}

/* 侧边栏 */
.sidebar {
  background-color: #1e293b;
  color: white;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  border-right: 1px solid #334155;
}

/* 自定义滚动条样式 */
.sidebar::-webkit-scrollbar {
  width: 6px;
}

.sidebar::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar::-webkit-scrollbar-thumb {
  background: #475569;
  border-radius: 3px;
  transition: background 0.3s ease;
}

.sidebar::-webkit-scrollbar-thumb:hover {
  background: #64748b;
}

/* Firefox 滚动条样式 */
.sidebar {
  scrollbar-width: thin;
  scrollbar-color: #475569 transparent;
}

.sidebar-header {
  padding: 1.5rem;
  border-bottom: 1px solid #334155;
}

.logo-container {
  display: flex;
  align-items: center;
}

.logo {
  width: 2.5rem;
  height: 2.5rem;
  background: linear-gradient(135deg, #3b82f6, #1e40af);
  border-radius: 0.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0.75rem;
}

.logo-icon {
  width: 1.5rem;
  height: 1.5rem;
  color: white;
}

.logo-text {
  font-size: 1.25rem;
  font-weight: 700;
  margin: 0;
}

/* 导航菜单 */
.sidebar-nav {
  flex: 1;
  padding: 1rem 0;
}

.nav-section {
  margin-bottom: 2rem;
}

.nav-section-title {
  font-size: 0.75rem;
  font-weight: 600;
  color: #94a3b8;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  padding: 0 1.5rem;
  margin-bottom: 0.5rem;
  margin-top: 0;
}

.nav-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-item {
  margin-bottom: 0.25rem;
}

.nav-link {
  display: flex;
  align-items: center;
  padding: 0.75rem 1.5rem;
  color: #cbd5e1;
  text-decoration: none;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
}

.nav-link:hover {
  background-color: #334155;
  color: white;
  border-left-color: #3b82f6;
}

.nav-link-active {
  background-color: #1e40af;
  color: white;
  border-left-color: #60a5fa;
}

.nav-icon {
  width: 1.25rem;
  height: 1.25rem;
  margin-right: 0.75rem;
}

/* 主容器 */
.main-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶栏 */
.top-header {
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 0 1.5rem;
  height: 4rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
}

.header-left {
  display: flex;
  align-items: center;
}

.sidebar-toggle {
  background: none;
  border: none;
  color: #64748b;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 0.375rem;
  margin-right: 1rem;
  transition: all 0.2s ease;
}

.sidebar-toggle:hover {
  background-color: #f1f5f9;
  color: #334155;
}

.toggle-icon {
  width: 1.25rem;
  height: 1.25rem;
}

.breadcrumb-item {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1e293b;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.header-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 0.375rem;
  transition: all 0.2s ease;
  position: relative;
}

.header-item:hover {
  background-color: #f8fafc;
}

.notification-item {
  position: relative;
}

.notification-icon-wrapper {
  position: relative;
}

.header-icon {
  width: 1.25rem;
  height: 1.25rem;
  color: #64748b;
}

.notification-badge {
  position: absolute;
  top: -0.5rem;
  right: -0.5rem;
  background-color: #ef4444;
  color: white;
  font-size: 0.75rem;
  border-radius: 9999px;
  width: 1.25rem;
  height: 1.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
}

.time-item {
  gap: 0.5rem;
}

.time-text {
  font-size: 0.875rem;
  color: #64748b;
}

.user-item {
  gap: 0.75rem;
  padding: 0.5rem 0.75rem;
}

.user-avatar {
  width: 2rem;
  height: 2rem;
  border-radius: 9999px;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 0.875rem;
  font-weight: 500;
  color: #1e293b;
  line-height: 1.2;
}

.user-role {
  font-size: 0.75rem;
  color: #64748b;
  line-height: 1.2;
}

.dropdown-icon {
  width: 1rem;
  height: 1rem;
  color: #94a3b8;
}

/* 页面内容 */
.page-content {
  flex: 1;
  overflow-y: auto;
  background-color: #f8fafc;
}

/* 通知面板 */
.notification-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 50;
  pointer-events: none;
}

.notification-content {
  position: absolute;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 10px 10px -5px rgb(0 0 0 / 0.04);
  width: 24rem;
  max-height: 32rem;
  overflow-y: auto;
  pointer-events: auto;
  border: 1px solid #e2e8f0;
}

.notification-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e2e8f0;
}

.notification-header h3 {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: #64748b;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 0.25rem;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background-color: #f1f5f9;
}

.close-icon {
  width: 1rem;
  height: 1rem;
}

.notification-list {
  padding: 0.5rem 0;
}

.notification-item {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #f1f5f9;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.notification-item:hover {
  background-color: #f8fafc;
}

.notification-item.unread {
  background-color: #eff6ff;
  border-left: 3px solid #3b82f6;
}

.notification-content-text h4 {
  font-size: 0.875rem;
  font-weight: 500;
  color: #1e293b;
  margin: 0 0 0.25rem 0;
}

.notification-content-text p {
  font-size: 0.75rem;
  color: #64748b;
  margin: 0 0 0.5rem 0;
  line-height: 1.4;
}

.notification-time {
  font-size: 0.75rem;
  color: #94a3b8;
}

/* 用户菜单面板 */
.user-menu-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 50;
  pointer-events: none;
}

.user-menu-content {
  position: absolute;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 10px 10px -5px rgb(0 0 0 / 0.04);
  padding: 0.5rem 0;
  min-width: 12rem;
  pointer-events: auto;
  border: 1px solid #e2e8f0;
}

.user-menu-item {
  display: flex;
  align-items: center;
  padding: 0.75rem 1rem;
  cursor: pointer;
  transition: background-color 0.2s ease;
  gap: 0.75rem;
}

.user-menu-item:hover {
  background-color: #f8fafc;
}

.user-menu-item.logout {
  color: #ef4444;
  border-top: 1px solid #f1f5f9;
  margin-top: 0.5rem;
  padding-top: 0.75rem;
}

.user-menu-item.logout:hover {
  background-color: #fef2f2;
}

.menu-icon {
  width: 1rem;
  height: 1rem;
}

/* 过渡动画 */
.notification-fade-enter-active,
.notification-fade-leave-active,
.user-menu-fade-enter-active,
.user-menu-fade-leave-active {
  transition: all 0.25s ease;
}

.notification-fade-enter-from,
.notification-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

.user-menu-fade-enter-from,
.user-menu-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.95);
}

.notification-fade-enter-to,
.notification-fade-leave-from,
.user-menu-fade-enter-to,
.user-menu-fade-leave-from {
  opacity: 1;
  transform: translateY(0) scale(1);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .home-layout {
    grid-template-columns: 1fr;
  }

  .sidebar {
    position: fixed;
    left: -280px;
    top: 0;
    height: 100vh;
    z-index: 40;
    transition: left 0.3s ease;
  }

  .sidebar.open {
    left: 0;
  }

  .main-container {
    grid-column: 1;
  }
}

@media (max-width: 768px) {
  .header-right {
    gap: 0.5rem;
  }

  .time-item {
    display: none;
  }

  .user-info {
    display: none;
  }

  .notification-content {
    width: 20rem;
  }
}
</style>